package com.itheima.web.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.system.Module;
import com.itheima.domain.system.User;
import com.itheima.domain.vx.Token;
import com.itheima.domain.vx.VxUser;
import com.itheima.service.system.UserService;
import com.itheima.utils.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.UUID;

@Controller
public class LoginController extends BaseController {
    @Reference
    private UserService userService;


    /*@RequestMapping("/login")
    public String login(String email, String password) {

        //1. 根据email调用service查询用户
        User user = userService.findByEmail(email);

        //2. 用户为空,说明用户不存在,提示错误,退出
        if (user == null) {
            request.setAttribute("error", "当前用户不存在");
            return "forward:/login.jsp";//强制不去拼接前后缀
        }

        //3. 判断密码, 如果密码比对失败,说明密码错误, 提示错误,退出
        String pass = new Md5Hash(password, email, 2).toString();
        if (!StringUtils.equals(pass, user.getPassword())) {
            request.setAttribute("error", "密码错误");
            return "forward:/login.jsp";//强制不去拼接前后缀
        }

        //4. 登录成功了
        //向session中存储用户信息
        session.setAttribute("loginUser", user);

        //根据用户查询对应的权限
        List<Module> moduleList = userService.findModuleByUser(user);
        session.setAttribute("modules", moduleList);

        //跳转主页面
        return "redirect:/home/main.do";
    }*/


    @RequestMapping("/login")
    public String login(String email, String password) {

        //1. 封装email和password为Token
        AuthenticationToken authenticationToken = new UsernamePasswordToken(email, new Md5Hash(password, email, 2).toString());

        //2. 获取Subject,并且调用login方法
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(authenticationToken);

            //3. 登录成功
            User user = (User) subject.getPrincipal();

            session.setAttribute("loginUser", user);

            List<Module> moduleList = userService.findModuleByUser(user);
            session.setAttribute("modules", moduleList);
            return "redirect:/home/main.do";

        } catch (Exception e) {
            request.setAttribute("error", "用户名或者密码错误");
            return "forward:/login.jsp";
        }
    }

    @RequestMapping("/home/main")
    public String main() {
        return "/home/main";
    }


    @RequestMapping("/weiXinLogin")
    public String weiXinLogin(String code) {
        Token token = new Token();
        try{
            //1.根据code获取access_token和openId
            String atUtl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3bdb1192c22883f3&secret=db9d6b88821df403e5ff11742e799105&code="+code+"&grant_type=authorization_code";
            String json = HttpUtil.sendGet(atUtl);
            token = JSON.parseObject(json, Token.class);

            //第二次回执获取用户信息
            String user_url="https://api.weixin.qq.com/sns/userinfo?access_token="+token.getAccess_token()+"&openid="+token.getOpenid();

            String s = HttpUtil.sendGet(user_url);
            VxUser vxUser = JSON.parseObject(s, VxUser.class);

            System.out.println(vxUser);

            User  user= userService.findByOpenId(vxUser.getOpenid());

            if (user==null){
                //微信新用户,进行注册
                user = new User();
                //设置主键
                user.setId(UUID.randomUUID().toString());
                user.setOpenid(vxUser.getOpenid());
                user.setUserName(vxUser.getNickname());
                if (vxUser.getSex().equals("2")) {
                    user.setGender("0");
                }else {
                    user.setGender("1");
                }

                user.setPic(vxUser.getHeadimgurl());
                String email=vxUser.getOpenid()+"@export.com";

                user.setEmail(email);

                String newPassword = new Md5Hash("123",email, 2).toString();

                user.setPassword(newPassword);

                user.setDegree(4);

//                user.setDeptId("100100");

                userService.save(user);

                return "redirect:/login.do?email="+email+"&password="+"123";
               // http://note.java.itcast.cn/login.do?email=oypcC1o5UIUzgtRqwpF1DVTwc2Kc@export.com&password=123
            }else {
                User user1 = userService.findByOpenId(vxUser.getOpenid());
                String email = user1.getEmail();
                String password = user1.getOldPassword();
                return "redirect:/login.do?email="+email+"&password="+password;
            }

        }catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/home/main";
    }

    @RequestMapping("/wxLogin")
    public String wxLogin() {
        String url="https://open.weixin.qq.com/connect/qrconnect?appid=wx3bdb1192c22883f3&redirect_uri=http%3A%2F%2Fnote.java.itcast.cn%2FweiXinLogin.do&response_type=code&scope=snsapi_login&state=null#wechat_redirect";
        return "redirect:"+url;
    }



    @RequestMapping("/home/home")
    public String home() {
        return "home/home";
    }

    //退出
    @RequestMapping(value = "/logout", name = "用户登出")
    public String logout() {
        SecurityUtils.getSubject().logout();   //登出
        return "redirect:/login.jsp";
    }
}

